package net.kucoe.grin;

import java.io.IOException;
import java.net.URL;
import java.util.logging.*;

import net.kucoe.grin.context.Context;
import net.kucoe.grin.context.ContextInitializer;
import net.kucoe.grin.context.application.GrinApplication;
import net.kucoe.grin.context.application.xml.ConfigurationProcessor;
import net.kucoe.grin.server.GrinServer;

/**
 * Main starter class for grin as standalone application.
 * 
 * @author Vitaliy Basyuk
 */
public class Grin {
    
    /**
     * Location of xml file for Grin context reading constant.
     */
    public static final String RESOURCE_LOCATION = "grin.context";
    
    /**
     * Grin log level constant.
     */
    public static final String LOG_LEVEL = "grin.log.level";
    
    /**
     * Grin server port constant.
     */
    public static final String SERVER_PORT = "grin.server.port";
    
    /**
     * Grin no server constant.
     */
    public static final String NO_SERVER = "grin.no.server";
    
    /**
     * Creates logger.
     * 
     * @param name
     * @return {@link Logger}
     */
    public static Logger getLogger(final String name) {
        Logger logger = Logger.getLogger("net.kucoe.grin." + name);
        String level = java.lang.System.getProperty(LOG_LEVEL, "info");
        Level logLevel = Level.parse(level.toUpperCase());
        logger.setLevel(logLevel);
        for (Handler handler : logger.getParent().getHandlers()) {
            if (handler instanceof ConsoleHandler) {
                handler.setLevel(logLevel);
            }
        }
        return logger;
    }
    
    /**
     * Start point method.
     * 
     * @param args
     * @throws ClassNotFoundException
     * @throws IOException
     */
    public static void main(final String[] args) throws ClassNotFoundException, IOException {
        String location = java.lang.System.getProperty(RESOURCE_LOCATION, "grin-context.xml");
        URL url = Grin.class.getClassLoader().getResource(location);
        ConfigurationProcessor configurationProcessor = new ConfigurationProcessor();
        GrinApplication application = configurationProcessor.processFile(url.getFile(), false);
        Context context = new ContextInitializer().initialize(application);
        context.start();
        String noserver = java.lang.System.getProperty(NO_SERVER, "false");
        if (!"true".equals(noserver)) {
            int port = getPropertyInt(SERVER_PORT, 8080);
            GrinServer server = Services.getServer();
            server.start(port);
        }
    }
    
    private static int getPropertyInt(final String property, final int defaultValue) {
        String prop = java.lang.System.getProperty(property, String.valueOf(defaultValue));
        int v = defaultValue;
        try {
            v = Integer.valueOf(prop);
        } catch (Exception e) {
            v = defaultValue;
        }
        return v;
    }
    
}
